package edu.tcc.iot.core.services.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;


import edu.tcc.iot.core.services.IShelfService;
import edu.tcc.iot.domain.Product;
import edu.tcc.iot.domain.Shelf;
import edu.tcc.iot.persistence.DBContext;
import edu.tcc.iot.persistence.dao.IShelfDAO;
import edu.tcc.iot.persistence.dao.IProductDAO;
import edu.tcc.iot.utils.ServiceLocator;

public class ShelfService implements IShelfService {

	private Logger log = Logger.getLogger(ShelfService.class);
	private DBContext dbContext = ServiceLocator.getInstance(DBContext.class);
	private IShelfDAO shelfDAO = ServiceLocator.getInstance(IShelfDAO.class);
	private IProductDAO productDAO = ServiceLocator.getInstance(IProductDAO.class);
	
	@Override
	public synchronized Shelf findById(long shelfId) throws SQLException {
		Shelf shelf = shelfDAO.findById(shelfId);
		if(shelf != null){
			List<Product> products = productDAO.findByShelf(shelfId);
			if(!products.isEmpty() || !products.isEmpty()){
				shelf.setProductList(products);
			}
		}
		return shelf;
	}

	@Override
	public synchronized Shelf saveShelf(Shelf shelf) throws SQLException {
		String sql = dbContext.getShelfQuery("dao.findby.id");
		PreparedStatement statement = dbContext.getConnection().prepareStatement(sql);
		statement.setLong(1, shelf.id);
		ResultSet shelfResultSet = statement.executeQuery();
		if(!shelfResultSet.first()){
			log.info("[CERS][ProductService] - Adding shelf " + shelf.toString());
			shelf = shelfDAO.add(shelf);
		}
		return shelf;
	}

	@Override
	public void addProductToShelf(Product product, long shelfId) {
		try {
			if(productDAO.exists(product)){
				productDAO.update(product);
				log.info("[CERS][ProductService] - Product updated " + product.getId());
			}else{
				productDAO.add(product, shelfId);
				log.info("[CERS][ProductService] - Product added " + product.getId());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
